<template>
  <div
    v-if="visible"
    class="flex fixed inset-0 z-50 justify-center items-center bg-black bg-opacity-50"
    @click="handleClose"
  >
    <div class="bg-white rounded-lg p-6 w-[1200px] relative" @click.stop>
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-semibold">位置信息</h3>
        <button @click="handleClose" class="text-gray-500 hover:text-gray-700">
          <svg
            class="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      </div>
      <div id="container" class="w-full h-[700px] rounded-lg"></div>
      <div class="flex mt-4 space-x-6 text-sm text-gray-600">
        <p>经度：{{ longitude }}</p>
        <p>纬度：{{ latitude }}</p>
        <p>地址：{{ address }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, watch } from "vue";

interface Props {
  visible: boolean;
  longitude: number;
  latitude: number;
  address: string;
}

const props = defineProps<Props>();
const emit = defineEmits(["update:visible"]);

let map: any = null;
let marker: any = null;

const handleClose = () => {
  emit("update:visible", false);
};

const initMap = () => {
  if (window.AMap) {
    map = new window.AMap.Map("container", {
      zoom: 15,
      center: [props.longitude, props.latitude],
    });

    marker = new window.AMap.Marker({
      position: [props.longitude, props.latitude],
      map: map,
    });
  }
};

watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 等待 DOM 更新后初始化地图
      setTimeout(() => {
        initMap();
      }, 0);
    }
  }
);

onUnmounted(() => {
  if (map) {
    map.destroy();
  }
});
</script>
